<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-[#141414] dark:via-[#1a1a1a] dark:to-[#141414] transition-colors duration-200">
    <!-- 头部 -->
    <Header />
    
    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
      <div class="max-w-4xl mx-auto">
        <router-view />
      </div>
    </main>
    
    <!-- 错误提示 -->
    <ErrorNotification />
    
    <!-- 退出确认对话框 -->
    <ExitConfirmDialog 
      :visible="showExitDialog"
      @confirm="handleExitConfirm"
      @cancel="handleExitCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import { useBandwidthStore } from '@/stores/bandwidth'
import { useSettingsStore } from '@/stores/settings'

import Header from '@/components/Header.vue'
import ErrorNotification from '@/components/ErrorNotification.vue'
import ExitConfirmDialog from '@/components/ExitConfirmDialog.vue'

const bandwidthStore = useBandwidthStore()
const settingsStore = useSettingsStore()

const showExitDialog = ref(false)

let statusInterval: number | null = null
let unlistenBackButton: (() => void) | null = null

// 合并后的isMobile判断（手机，非平板）
function isMobile() {
  return (/Mobi|Android|iPhone/i.test(navigator.userAgent) && !/iPad|Tablet/i.test(navigator.userAgent)) ||
    (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && !/iPad|Tablet/i.test(navigator.userAgent));
}
// 判断是否为平板
function isTablet() {
  return /iPad|Tablet|Nexus 7|Nexus 10|SM-T|Lenovo Tab|XiaoMiPad/i.test(navigator.userAgent);
}

function lockPortrait() {
  // 只在支持的浏览器下调用
  if (screen.orientation && (screen.orientation as any).lock) {
    (screen.orientation as any).lock('portrait').catch(() => {});
  }
}

if (isMobile() && !isTablet()) {
  // 尝试锁定竖屏
  lockPortrait();
  // 监听方向变化，强制竖屏
  window.addEventListener('orientationchange', () => {
    lockPortrait();
  });
}

// 禁用右键菜单
const disableContextMenu = (event: MouseEvent) => {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用特定键盘快捷键
const disableKeyboardShortcuts = (event: KeyboardEvent) => {
  // 禁用F12, Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+U, Ctrl+S, Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
  if (
    event.key === 'F12' ||
    (event.ctrlKey && event.shiftKey && (event.key === 'I' || event.key === 'J')) ||
    (event.ctrlKey && (event.key === 'u' || event.key === 'U')) ||
    (event.ctrlKey && (event.key === 's' || event.key === 'S')) ||
    (event.ctrlKey && (event.key === 'a' || event.key === 'A')) ||
    (event.ctrlKey && (event.key === 'c' || event.key === 'C')) ||
    (event.ctrlKey && (event.key === 'v' || event.key === 'V')) ||
    (event.ctrlKey && (event.key === 'x' || event.key === 'X')) ||
    (event.ctrlKey && (event.key === 'r' || event.key === 'R')) ||
    (event.ctrlKey && (event.key === 'w' || event.key === 'W'))
  ) {
    event.preventDefault()
    event.stopPropagation()
    return false
  }
  
  // 禁用Ctrl++, Ctrl+-, Ctrl+0 (缩放)
  if (event.ctrlKey && (event.key === '+' || event.key === '-' || event.key === '0')) {
    event.preventDefault()
    event.stopPropagation()
    return false
  }
  
  return true
}

// 禁用拖拽
const disableDrag = (event: DragEvent) => {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用选择
const disableSelection = (event: Event) => {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用双击选择
const disableDoubleClick = (event: MouseEvent) => {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用移动端的触摸事件
const disableTouchEvents = (event: TouchEvent) => {
  // 如果是多点触控（缩放），则禁用
  if (event.touches.length > 1) {
    event.preventDefault()
    event.stopPropagation()
    return false
  }
  return true
}

// 处理退出确认
const handleExitConfirm = async () => {
  try {
    // 先停止当前的带宽控制任务
    if (bandwidthStore.isRunning) {
      await bandwidthStore.stopBandwidthConsumption()
    }
    
    // 调用退出应用命令
    await invoke('exit_app')
  } catch (error) {
    console.error('退出应用失败:', error)
    showExitDialog.value = false
  }
}

// 处理取消退出
const handleExitCancel = () => {
  showExitDialog.value = false
}



// 处理移动端返回键
const handleBackButton = () => {
  console.log('检测到返回键，显示退出确认对话框')
  showExitDialog.value = true
}

onMounted(async () => {
  // 初始化设置store（必须在bandwidth store之前）
  settingsStore.initialize()
  
  await bandwidthStore.initialize()
  
  // 每秒更新状态
  statusInterval = setInterval(() => {
    bandwidthStore.fetchStatus()
  }, 1000)
  
  // 禁用用户交互
  document.addEventListener('contextmenu', disableContextMenu)
  document.addEventListener('keydown', disableKeyboardShortcuts)
  document.addEventListener('dragstart', disableDrag)
  document.addEventListener('selectstart', disableSelection)
  document.addEventListener('dblclick', disableDoubleClick)
  
  // 移动端特定的事件监听
  if (isMobile()) {
    document.addEventListener('touchstart', disableTouchEvents, { passive: false })
    document.addEventListener('touchmove', disableTouchEvents, { passive: false })
    document.addEventListener('gesturestart', disableSelection, { passive: false })
    document.addEventListener('gesturechange', disableSelection, { passive: false })
    document.addEventListener('gestureend', disableSelection, { passive: false })
  }
  
  // 如果是移动端，监听返回键事件
  if (isMobile()) {
    try {
      // 监听Android返回键事件
      unlistenBackButton = await listen('android-back-button', () => {
        handleBackButton()
      })
      console.log('已设置移动端返回键监听')
      
      // 初始化移动端
      await invoke('init_mobile')
    } catch (error) {
      console.error('设置移动端返回键监听失败:', error)
    }
  }
  
  // 监听浏览器的beforeunload事件（桌面端和移动端WebView）
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (bandwidthStore.isRunning) {
      event.preventDefault()
      event.returnValue = '您有正在运行的带宽控制任务，确定要退出吗？'
      return event.returnValue
    }
  }
  

  
  // 监听移动端的物理返回键（Android WebView）
  const handlePopstate = (event: PopStateEvent) => {
    if (isMobile()) {
      event.preventDefault()
      handleBackButton()
      // 阻止默认的返回行为
      history.pushState(null, '', location.href)
    }
  }
  
  // 添加事件监听器
  window.addEventListener('beforeunload', handleBeforeUnload)
  window.addEventListener('popstate', handlePopstate)
  
  // 为移动端设置初始历史状态
  if (isMobile()) {
    history.pushState(null, '', location.href)
  }
  
  // 清理函数
  const cleanup = () => {
    // 移除用户交互禁用的事件监听器
    document.removeEventListener('contextmenu', disableContextMenu)
    document.removeEventListener('keydown', disableKeyboardShortcuts)
    document.removeEventListener('dragstart', disableDrag)
    document.removeEventListener('selectstart', disableSelection)
    document.removeEventListener('dblclick', disableDoubleClick)
    
    if (isMobile()) {
      document.removeEventListener('touchstart', disableTouchEvents)
      document.removeEventListener('touchmove', disableTouchEvents)
      document.removeEventListener('gesturestart', disableSelection)
      document.removeEventListener('gesturechange', disableSelection)
      document.removeEventListener('gestureend', disableSelection)
    }
    
    window.removeEventListener('beforeunload', handleBeforeUnload)
    window.removeEventListener('popstate', handlePopstate)
  }
  
  // 在组件卸载时清理
  return cleanup
})

onMounted(async () => {
  // Listen for autostart changes from the backend (e.g., tray menu)
  await listen<boolean>('autostart-changed', (event) => {
    console.log('Autostart status changed from backend:', event.payload)
    settingsStore.syncAutostartState(event.payload)
  })
})

onUnmounted(() => {
  if (statusInterval) {
    clearInterval(statusInterval)
  }
  
  if (unlistenBackButton) {
    unlistenBackButton()
  }
})
</script> 